<template>
	<view style="height: 100%;">
		<!-- ====== begin 过滤功能 ====== -->
		<view class="sort">
			<view :class="{on: sortCur==2}" @click="onChangeSort(2)">我的报名</view>
			<view :class="{on: sortCur==3}" @click="onChangeSort(3)">我的发布</view>
		</view>
		<!-- ====== end 过滤功能 ====== -->
		
		<view v-for="(race, index) in races" class="bk-white radius2 mg-md pd-md" >
			<view class="lay-c-c">
				<!-- <image style="width: 150upx; height: 150upx; border-radius: 16rpx; " :mode="imgMode" :src="race.raceAvatar">
				</image> -->
				<view style="flex: 1; margin: 0rpx 20rpx; ">
					<view>
						<text style="font-weight: bold; color: #333333; font-size: 36upx;">{{race.raceName}}</text>
					</view>
					<!-- <view style="margin: 20rpx 0rpx; font-size: small;">报名时间：{{race.raceDate}} 至 {{race.raceDate}}</view> -->
					<view style="margin: 20rpx 0rpx; font-size: small;">报名时间：{{race.matchInfo[0]['desc']}}</view>
					<view style="margin: 20rpx 0rpx; font-size: small;">比赛时间：{{race.raceDate}}<text v-if="race.active==-2">已结束</text></view>
					<view style="margin: 20rpx 0rpx; font-size: small;">比赛地点：{{race.raceAddress}}</view>
					<view style="margin: 20rpx 0rpx; font-size: small;">比赛人数：{{race.signUpCount}}/{{race.numOfPlayers}}</view>
					<button v-if="sortCur==2 && race.active==1 && race.signInState==0" class="btn bk-orange white mg-r-md mg-b-md" size="default" @click="onTapSignIn(race.raceId)">签到</button>
					<button v-if="sortCur==2 && race.active==1 && race.signInState==1" class="btn bk-bk-green white mg-r-md mg-b-md" size="default">已签到</button>
					<button v-if="sortCur==2 && race.active>=2 && race.active%2 == 0" class="btn bk-orange white mg-r-md mg-b-md" size="default" @click="goDrawLots(race)">比赛抽签</button>
					<button v-if="sortCur==3 && race.active==-1" class="btn bk-orange white mg-r-md mg-b-md" @click="openSignUp(race.raceId)">开启报名</button>
					<!-- <button v-if="sortCur==3 && race.active==0" class="btn bk-orange white mg-r-md" @click="closeSignUp(race.raceId)">关闭报名</button> -->
					<button v-if="sortCur==3 && race.active==0" class="btn bk-orange white mg-r-md mg-b-md" @click="signUpList(race,race.raceId)">报名名单</button>
					<button v-if="sortCur==3 && race.active==0" class="btn bk-orange white mg-r-md mg-b-md" @click="openSignIn(race.raceId)">开启签到</button>
					<!-- <button v-if="sortCur==3 && race.active==1" class="btn bk-orange white mg-r-md" @click="closeSignIn(race.raceId)">关闭签到</button> -->
					<button v-if="sortCur==3 && race.active==1" class="btn bk-orange white mg-r-md mg-b-md" @click="signInList(race,race.raceId)">签到名单</button>
					<button v-if="sortCur==3 && race.signin && race.active>-2" class="btn bk-orange white mg-r-md margin mg-b-md" @click="openLottery(race.raceId)">开启抽签</button>
					<button v-if="sortCur==3 && race.signin && race.active>-2" class="btn bk-orange white mg-r-md margin mg-b-md" @click="lotteryList(race,race.raceId)">抽签名单</button>
					<button v-if="sortCur==3 && race.signup && race.active>-2" class="btn bk-orange white mg-r-md margin mg-b-md" @click="openRace(race.raceId)">开启比赛</button>
					<button v-if="sortCur==3" class="btn bk-orange white mg-r-md mg-b-md" @click="goRaceManage(race)">赛事管理</button>
					
					<uni-steps v-if="race.active>-2" :options="race.matchInfo" direction="column" :active="race.active"></uni-steps>
					<button v-if="sortCur==2" class="btn bk-orange white mg-r-md margin" @click="showResult(race,race.raceId)">成绩查询</button>
					<!-- <view v-if="sortCur==2" style="margin: 20rpx 0rpx; font-size: small;">审核状态：<text class="green">{{race.auditState==1?'审核通过':'待审核'}}</text></view>
					<view v-else style="margin: 20rpx 0rpx; font-size: small;">比赛人数：{{race.signUpCount}}/{{race.numOfPlayers}}</view> -->
				</view>
			</view>
			<view v-if="sortCur==2" class="lay-fe-c">
				<!-- <button v-if="race.auditState" class="btn bk-orange white mg-r-md" @click="goDrawLots(race)">比赛抽签</button> -->
				<!-- <button class="btn bk-blue white mg-r-md">报名详情</button> -->
				<!-- <button class="btn bk-blue white mg-r-md" @click="goRaceDetail(race)">查看详情</button> -->
			</view>
			<view v-else class="lay-fe-c">
				<!-- <button class="btn bk-orange white mg-r-md" @click="goRaceManage(race)">赛事管理</button> -->
				<!-- <button class="btn bk-blue white mg-r-md" @click="goRaceDetail(race)">查看详情</button> -->
			</view>
		</view>
		
		<!-- ====== begin 授权功能 ====== -->
		<!-- #ifdef MP -->
		<authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
		<!-- #endif -->
		<!-- #ifndef H5 -->
		<passwordPopup></passwordPopup>
		<!-- #endif -->
		<!-- ====== end 授权功能 ====== -->
		
		<!-- ====== begin 悬浮按钮 ====== -->
		<view v-if="sortCur==3" class="fix-btn add" @click="onTapAddRace">
			<text>发布</text>
			<text>比赛</text>
		</view>
		<!-- ====== end 悬浮按钮 ====== -->
	</view>
</template>

<script>
	import { setStorage, getStorage, removeStorage, Modal } from '../../libs/uniApi.js';
	import {
		MyTip
	} from '@/components/ssty/common.js';
	import {
		querySlideImgs,
		queryRaces,
		openLottery,
		signIn,
		changeRaceSignStatus,
	} from '@/api/fsh.js';
	const app = getApp();

	// ====== begin 授权功能 ======
	import {
		mapGetters
	} from "vuex";
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	// #ifndef H5
	import passwordPopup from '@/components/passwordPopup';
	// #endif
	// ====== end 授权功能 ======
	
	export default {
		// ====== begin 授权功能 ======
		components: {
			// #ifndef H5
			passwordPopup,
			// #endif
			// #ifdef MP
			authorize
			// #endif
		},
		// ====== end 授权功能 ======
		
		data() {
			return {				
				// ====== begin 授权功能 ======
				isAuto: false,
				isShowAuth: false,
				// ====== end 授权功能 ======
				
				
				// ====== begin 过滤功能 ======
				sortCur: 2,
				// ====== end 过滤功能 ======
				
				// ====== begin FshGround列表功能 ======
				imgMode: 'aspectFit',
				races: [],
				// ====== begin ScrollView加载更多功能 ======
				pageNum: 1,
				pageCount: 1,
				loadMoreText: "上拉加载更多",
				// ====== end ScrollView加载更多功能 ======
				// ====== end FshGround列表功能 ======
			}
		},
		computed: {
			// ====== begin 授权功能 ======
			...mapGetters(['isLogin']),
			// ====== end 授权功能 ======
		},
		onLoad() {			
			this.onChangeSort(2);
		},
		onShow() {
			this.onChangeSort(this.sortCur); // 删除比赛回退到此页面时，重新加载
		},
		methods: {
			showResult(race,raceId){
				app.globalData.tempParam_for_raceManage = race;
				uni.navigateTo({
					url: `/pages/fsh_race/race_score?raceId=${raceId}`
				})
			},
			signUpList(race,raceId){
				app.globalData.tempParam_for_raceManage = race;
				uni.navigateTo({
					url: "/pages/fsh_race/race_manage_sign_up?raceId="+raceId+"&prodId=&merId="
				})
			},
			signInList(race,raceId){
				app.globalData.tempParam_for_raceManage = race;
				uni.navigateTo({
					url: "/pages/fsh_race/race_manage_sign_in?raceId="+raceId+"&prodId=&merId="
				})
			},
			lotteryList(race,raceId){
				app.globalData.tempParam_for_raceManage = race;
				uni.navigateTo({
					url: "/pages/fsh_race/race_manage_edit_draw_lots_list?raceId="+raceId+"&prodId=&merId="
				})
			},
			onTapSignIn(raceId) {
				signIn(raceId).then(res=>{
					Modal('已签到', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err=>{
					console.log("signIn fail:", err);
				})
			},
			
			openSignIn(raceId) {
				changeRaceSignStatus(raceId, 1, 0, 1).then(res=>{
					Modal('已开启签到', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err=>{
					console.log("changeRaceSignStatus fail, err=%o", err)
				})
			},
			
			closeSignIn(raceId) {
				changeRaceSignStatus(raceId, 1, 1, 2).then(res=>{
					Modal('已关闭签到', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err=>{
					console.log("changeRaceSignStatus fail, err=%o", err)
				})
			},
			
			openSignUp(raceId) {
				changeRaceSignStatus(raceId, 0, 0, 1).then(res => {
					Modal('已开启报名', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err => {
					console.log("changeRaceSignStatus fail, err=%o", err)
					MyTip(err.msg);
				})
			},
			
			closeSignUp(raceId) {
				changeRaceSignStatus(raceId, 0, 1, 0).then(res => {
					Modal('已关闭报名', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err => {
					console.log("changeRaceSignStatus fail, err=%o", err)
					MyTip(err.msg);
				})
			},
			
			openLottery(raceId) {
				openLottery(raceId, "1").then(res=>{
					Modal('已开启', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err=>{
					console.log(err)
					Modal('开启失败，请稍后重试。'+err.msg, '', {showCancel: false})
					.then(() => {
					})
				})
			},
			
			openRace(raceId) {
				openLottery(raceId, "2").then(res=>{
					Modal('已开启', '', {showCancel: false})
					.then(() => {
						this.onChangeSort(this.sortCur);
					})
				}).catch(err=>{
					Modal('开启失败，请稍后重试。'+err.msg, '', {showCancel: false})
					.then(() => {
					})
				})
			},
			// ====== begin 授权功能 ======
			// 打开授权
			openAuto() {
				this.isAuto = true;
				this.isShowAuth = true;
				console.log("openAuto, this.isShowAuth=true");
			},
			// 授权回调
			onLoadFun(userInfo) {
				console.log("onLoadFunc, userInfo:", userInfo);
				if(userInfo) { // 得到userInfo，说明登录成功，隐藏授权；否则继续显示授权
					this.isShowAuth = false;
					this.onChangeSort(2);
				}
			},
			// 授权关闭
			authColse: function(e) {
				this.isShowAuth = e
				console.log("authColse, this.isShowAuth="+this.isShowAuth);
			},
			// ====== end 授权功能 ======
			
			
			// ====== begin 过滤功能 ======
			onChangeSort(sortNew) {
				this.sortCur = sortNew;
				
				this.loadRaces(sortNew);
			},
			// ====== end 过滤功能 ======
			
			loadRaces(queryType=2, pageNum=1) {
				if(!this.isLogin) {
					console.log("open auth")
					this.openAuto();
					return;
				}
				
				// uni.showLoading({
				// 	title: '努力加载中...'
				// });
				queryRaces(queryType, 1, pageNum).then(res => {
					// uni.hideLoading();
					console.log("race_list::loadRaces ok, res=%o", res)
					
					this.imgMode = res.entity.imgMode;
					this.matchInfo = [];
					for(let item in res.entity.list){
						let matchInfo = [];
						let rstart = this.timestampToTime(new Date(res.entity.list[item].signFromTime).getTime(),1);
						let rend = this.timestampToTime(new Date(res.entity.list[item].signToTime).getTime(),1);
						let rdesc = "";
						if(rstart==rend){
							rdesc = rstart;
						}else{
							rdesc = rstart + " 至 " + rend;
						}
						let audit = "";
						let color = "blue";
						if(this.sortCur==2){
							if(res.entity.list[item].auditState){
								if(res.entity.list[item].auditState == "1"){
									audit = " 审核通过";
									color = "green";
								}else{
									audit = " 未通过审核";
									color = "red";
								}
							}else{
								audit = "正在审核中";
							}
						}
						matchInfo.push({"title":"比赛报名","desc":rdesc,"audit":audit,"color":color})
						matchInfo.push({"title":"比赛签到","desc":res.entity.list[item].raceDate})
						// if(res.entity.list[item].active<2){
						// 	matchInfo.push({"title":"比赛抽签","desc":this.timestampToTime(new Date(res.entity.list[item].raceLotteryTime).getTime(),2)})
						// }else if(res.entity.list[item].active==-2){
						// 	matchInfo.push({"title":"比赛抽签","desc":"结束"})
						// }else{
						// 	matchInfo.push({"title":"比赛抽签","desc":"待启动"})
						// }
						try{
							let r = JSON.parse(res.entity.list[item].rounds) 
							let roundInfoes = res.entity.list[item].roundInfo.split(",")
							let ltime = new Date(res.entity.list[item].raceLotteryTime);
							ltime = ltime.getTime();
							res.entity.list[item]["signin"] = false;
							res.entity.list[item]["signup"] = false;
							if(res.entity.list[item].active==1 && res.entity.list[item]['curr_round']*1==0){
								res.entity.list[item]["signin"] = true;
							}
							for(let round in r){
								let roundInfo = roundInfoes[round].split("_")
								// ltime = ltime+(round*(r[round]['prepair']*1+r[round]['matchTime']*1)*60)*1000;
								ltime = new Date(roundInfo[4]);
								ltime = ltime.getTime();
								let lstart = this.timestampToTime(ltime,2);
								let mstart = this.timestampToTime(ltime + (r[round]['prepair']*60*1000),2);
								let mend = this.timestampToTime(ltime + (r[round]['prepair']*60*1000) + (r[round]['matchTime']*60*1000),2);
								if(res.entity.list[item]['curr_round']*1==round*1+1){
									if(roundInfo[2]==0){
										res.entity.list[item]["signin"] = true;
									}
									if(roundInfo[3]<2){
										res.entity.list[item]["signup"] = true;
										matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备","desc":lstart+" 至 "+mstart})
										matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":mstart+" 至 "+mend})
									}else if(roundInfo[3]==2){
										matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备","desc":lstart+" 至 "+this.timestampToTime(new Date(roundInfo[0]).getTime(),2)})
										matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 至 "+this.timestampToTime(new Date(roundInfo[1]).getTime(),2)})
									}else{
										res.entity.list[item]["signin"] = true;
										matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备", "desc":lstart+" 至 "+this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 已结束"})
										matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 至 "+this.timestampToTime(new Date(roundInfo[1]).getTime(),2)+" 已结束"})
									}
								}else if(res.entity.list[item]['curr_round']*1>round*1+1){
									matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备", "desc":lstart+" 至 "+this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 已结束"})
									matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 至 "+this.timestampToTime(new Date(roundInfo[1]).getTime(),2)+" 已结束"})
								}else{
									matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备", "desc":"待定"})
									matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":"待定"})
								}
								//race_round_status: 0-not start, 1-draw lottery done and activated, 2-start race, 3-end race
								// if(this.sortCur==3 && roundInfo[2]==0){
								// 	res.entity.list[item]["signin"] = true;
								// }
								// if(roundInfo[3]==1){
								// 	res.entity.list[item]["signup"] = true;
								// 	if(this.sortCur==3 && res.entity.list[item].active>=2){
								// 		// res.entity.list[item]["signin"] = true;
								// 		// res.entity.list[item]["signup"] = false;
								// 	}
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备", "desc":"待定"})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":"待定"})
								// }else if(roundInfo[3]<2){
								// 	if(this.sortCur==3 && res.entity.list[item].active>=2){
								// 		// res.entity.list[item]["signin"] = false;
								// 		// res.entity.list[item]["signup"] = true;
								// 	}
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备","desc":lstart+" 至 "+mstart})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":mstart+" 至 "+mend})
								// }else if(roundInfo[3]<3){
								// 	if(this.sortCur==3 && res.entity.list[item].active>=2){
								// 		// res.entity.list[item]["signin"] = false;
								// 		// res.entity.list[item]["signup"] = false;
								// 	}
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备","desc":lstart+" 至 "+mstart})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 至 "+this.timestampToTime(new Date(roundInfo[1]).getTime(),2)})
								// }else if(roundInfo[3]>0){
								// 	if(this.sortCur==3 && res.entity.list[item].active>=2){
								// 		// res.entity.list[item]["signin"] = false;
								// 		// res.entity.list[item]["signup"] = false;
								// 	}
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前抽签及准备", "desc":lstart+" 至 "+mstart+" 已结束"})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":this.timestampToTime(new Date(roundInfo[0]).getTime(),2)+" 至 "+this.timestampToTime(new Date(roundInfo[1]).getTime(),2)+" 已结束"})
								// }
								// if(res.entity.list[item].active>=2){
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前准备","desc":lstart+" 至 "+mstart})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":roundInfo[0]+" 至 "+roundInfo[1]})
								// }else if(res.entity.list[item].active==-2){
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前准备", "desc":"结束"})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":"结束"})
								// }else{
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场赛前准备", "desc":"待定"})
								// 	matchInfo.push({"title":"第"+(round*1+1)+"场比赛开赛", "desc":"待定"})
								// }
							}
						}catch(e){
							console.log(e)
						}
						res.entity.list[item].matchInfo = matchInfo;
					}
					this.races = res.entity.list;
					
					// ====== begin ScrollView加载更多功能 ======
					this.pageNum = 1;
					this.pageCount = res.entity.pageCount;
					this.loadMoreText = (this.pageNum < this.pageCount) ? "上拉加载更多" : "~ 没有更多数据了 ~";
					// ====== end ScrollView加载更多功能 ======
				}).catch(err => {
					// uni.hideLoading();
					console.log("race_list::loadRaces fail, err=%o", err)
					MyTip(err.msg);
				});
			},
			
			timestampToTime(timestamp, needTime) {
			  // 时间戳为10位需*1000，时间戳为13位不需乘1000
			  var date = new Date(timestamp);
			  var Y = date.getFullYear() + "-";
			  var M =
			    (date.getMonth() + 1 < 10
			      ? "0" + (date.getMonth() + 1)
			      : date.getMonth() + 1) + "-";
			  var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
			  var h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
			  var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
			  var s = (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
			  if(needTime == 1){
				  return Y + M + D;
			  }else if(needTime == 2){
				  return h + m + s;
			  }else{
				  return Y + M + D + h + m + s;
			  }
			  
			},
			
			// 进入抽签页面
			goDrawLots(item) {
				uni.navigateTo({
					url: `/pages/fsh_race/draw_lots?raceId=${item.raceId}`
				})
			},
			
			// 进入比赛管理页面
			goRaceManage(item) {
				app.globalData.tempParam_for_raceManage = item;
				console.log("goRaceManage ..., tempParam_for_raceManage=", app.globalData.tempParam_for_raceManage);
				uni.navigateTo({
					url: `/pages/fsh_race/race_manage?raceId=${item.raceId}&raceName=${item.raceName}&prodId=${item.prodId}&merId=${item.merId}`
				})
			},
			
			// 进入比赛详情页
			goRaceDetail(item) {
				uni.navigateTo({
					url: `/pages/fsh_race/race_detail?raceId=${item.raceId}&prodId=${item.prodId}&merId=${item.merId}`
				})
			},
			
			onTapAddRace() {
				uni.navigateTo({
					url: `/pages/fsh_race/race_manage_edit_info?scene=1`
				})
			},
			
			onSearch() {
				console.log("search: "+this.searchKey);
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/leui.scss";
	
	page {
		height: 100%;
		background-color: #f5f5f5;
	}
	
	// ====== begin 过滤功能 ======
	.sort {
		display: flex;
		justify-content: space-around;
		background-color: white;
		view {
			padding: 20rpx 20rpx;
		}
		
		.on {
			color: red;
			border-bottom: 1rpx solid red;
		}
	}
	.margin {
		margin-left: 10px;
	}
	// ====== end 过滤功能 ======
	
	// ====== begin 悬浮按钮 ======
	.fix-btn {
		position: fixed;
		top: px;
		right: 20px;
		z-index: 1;
		color: #FFFFFF;
		background-color: #e8822a;
		
		width: 110rpx;
		height: 110rpx;
		border-radius: 110rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.fix-btn.add {
		bottom: 40px;
	}
	// ====== end 悬浮按钮 ======
</style>
